package com.javaee.ch12.common.base;

import java.util.ArrayList;
import java.util.List;

public class GenericDao<T extends BaseEntity> {
    private List<T> entities = new ArrayList<>();
    private Long currentId = 1L;

    // 添加实体对象
    public synchronized void addEntity(T entity) {
        entity.setId(currentId++);
        entities.add(entity);
    }

    // 根据id删除实体对象
    public boolean deleteEntityById(Long id) {
        return entities.removeIf(entity -> id.equals(entity.getId()));
    }

    // 根据id查询实体对象
    public T getEntityById(Long id) {
        for (T entity : entities) {
            if (id.equals(entity.getId())) {
                return entity;
            }
        }
        return null;  // 如果没有找到
    }

    // 获取所有实体对象
    public List<T> getAllEntities() {
        return entities;
    }

    // 修改实体对象
    public boolean updateEntity(T updatedEntity) {
        Long id = updatedEntity.getId();
        for (int i = 0; i < entities.size(); i++) {
            T entity = entities.get(i);
            if (id.equals(entity.getId())) {
                entities.set(i, updatedEntity);
                return true;
            }
        }
        return false;
    }
}
